# coding=utf8
__author__ = 'lijian'
from packet import *
import time
import config

__seq = 0


def seqGen():
    global __seq

    value = __seq
    __seq += 1
    if __seq > 15:
        __seq = 0
    return value


# 构建主动站包
def buildInitiativeFrame(cmd, dataUnit, aux=None):
    afn = AFN(dir=1, prm=1, acd=0, cmd=cmd)

    if not aux:
        seq = SEQ(tpv=0, fir=1, fin=1, con=1, seq=seqGen())
    else:
        seq = SEQ(tpv=1, fir=1, fin=1, con=1, seq=seqGen())

    dataRegion = FrameDataRegion(afn, seq, dataUnit, aux)
    frame = Frame(dataRegion, config.info["address"])
    return frame


# 构建被动站包
def buildPassiveFrame(cmd, dataUnit, seq):
    afn = AFN(dir=1, prm=0, acd=0, cmd=cmd)
    seq = SEQ(tpv=0, fir=1, fin=1, con=0, seq=seq.Seq)
    aux = None
    dataRegion = FrameDataRegion(afn, seq, dataUnit, aux)
    frame = Frame(dataRegion, config.info["address"])
    return frame


# 确认
def ACK(frame):
    pseq = frame.dataRegion.SEQ
    afn = AFN(dir=0, prm=0, acd=0, cmd=00)
    seq = SEQ(tpv=0, fir=1, fin=1, con=0, seq=pseq.Seq)

    dataUnit = DataUnit(0, 1, None)
    dataRegion = FrameDataRegion(afn, seq, dataUnit)
    ack = Frame(dataRegion, config.info["address"])
    return ack


# 否认
def NAK(frame):
    pseq = frame.dataRegion.SEQ

    afn = AFN(dir=0, prm=0, acd=0, cmd=00)
    seq = SEQ(tpv=0, fir=1, fin=1, con=1, seq=pseq.Seq)
    aux = None

    dataUnit = DataUnit(0, 2, None)
    dataRegion = FrameDataRegion(afn, seq, dataUnit, aux)
    ack = Frame(dataRegion, config.info["address"])
    return ack